package cn.lzx.hrm.service.impl;

import cn.lzx.constants.LoginConstants;
import cn.lzx.dto.LoginDto;
import cn.lzx.exctption.ValidUtil;
import cn.lzx.hrm.domain.LoginUser;
import cn.lzx.hrm.mapper.LoginUserMapper;
import cn.lzx.hrm.service.ILoginUserService;
import cn.lzx.util.AjaxResult;
import cn.lzx.util.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-01-04
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;


    @Override
    public AjaxResult getAccount(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        Integer type = loginDto.getType();
        List<LoginUser> loginUsers = loginUserMapper.selectList(new EntityWrapper<LoginUser>().eq("username", username));
        //参数校验
        ValidUtil.assertListNotNull(loginUsers, "请输入正确用户名或密码！");
        // 方案1：写死clientid和写死clientid和client
        String clientId = "website";
        String clientSecret = "1";
        if (type.longValue() == 0) {
            clientId = "admin";
            clientSecret = "1";
        }
            String pwdAuthUrl = String.format(LoginConstants.PASSWORD_AUTH_URL,
                    clientId, clientSecret, loginDto.getUsername(), loginDto.getPassword());
            Map<String, Object> map = HttpUtil.sendPost(pwdAuthUrl);
            //错误判断
            String error = (String) map.get("error");
            String message = (String) map.get("error_description");
            ValidUtil.assertNull(error, message);
            //成功后获取token和refreshToken
            String token = (String) map.get("access_token");
            String refreshToken = (String) map.get("refresh_token");

            //构造返回值
            HashMap<String, String> result = new HashMap<>();
            result.put("token", token);
            result.put("refreshToken", refreshToken);
            return AjaxResult.me().setResultObj(result);
        }
}
